"""
测试增强版XML_Utils处理SOAP命名空间XML报文的功能
"""

import tempfile
import os
from com.tools.Xml_Utils.xml_utils import XmlUtils


def test_enhanced_soap_features():
    """
    测试增强的SOAP功能
    """
    print("测试增强的SOAP功能:")
    
    # 创建临时目录用于测试
    with tempfile.TemporaryDirectory() as temp_dir:
        # 测试创建SOAP信封
        print("\n1. 测试创建SOAP信封:")
        xml_obj = XmlUtils.create_empty_xml()
        xml_obj.create_soap_envelope({
            'web': 'http://www.webserviceX.NET'
        })
        
        # 验证SOAP结构
        envelope = xml_obj.find_element(".")
        print(f"根元素: {envelope.tag}")
        assert envelope.tag == "{http://schemas.xmlsoap.org/soap/envelope/}Envelope"
        
        header = xml_obj.find_element(".//{http://schemas.xmlsoap.org/soap/envelope/}Header")
        body = xml_obj.find_element(".//{http://schemas.xmlsoap.org/soap/envelope/}Body")
        print(f"Header元素存在: {header is not None}")
        print(f"Body元素存在: {body is not None}")
        assert header is not None
        assert body is not None
        
        # 测试添加SOAP Header元素
        print("\n2. 测试添加SOAP Header元素:")
        auth_element = xml_obj.add_soap_header_element(
            "Authentication", 
            namespace="http://www.webserviceX.NET",
            attributes={"type": "apiKey"}
        )
        auth_element.text = "ABC123XYZ"
        
        # 验证Header元素
        auth_in_xml = xml_obj.find_element(".//{http://www.webserviceX.NET}Authentication")
        print(f"认证元素存在: {auth_in_xml is not None}")
        print(f"认证元素文本: {auth_in_xml.text}")
        print(f"认证元素属性: {auth_in_xml.attrib}")
        assert auth_in_xml is not None
        assert auth_in_xml.text == "ABC123XYZ"
        assert auth_in_xml.attrib["type"] == "apiKey"
        
        # 测试添加SOAP Body元素
        print("\n3. 测试添加SOAP Body元素:")
        request_element = xml_obj.add_soap_body_element(
            "GetWeather", 
            namespace="http://www.webserviceX.NET"
        )
        
        # 添加子元素
        city_element = ET.SubElement(request_element, "{http://www.webserviceX.NET}CityName")
        city_element.text = "Beijing"
        
        country_element = ET.SubElement(request_element, "{http://www.webserviceX.NET}CountryName")
        country_element.text = "China"
        
        # 验证Body元素
        weather_request = xml_obj.find_element(".//{http://www.webserviceX.NET}GetWeather")
        print(f"天气请求元素存在: {weather_request is not None}")
        
        city_name = xml_obj.get_element_text(".//{http://www.webserviceX.NET}CityName")
        country_name = xml_obj.get_element_text(".//{http://www.webserviceX.NET}CountryName")
        print(f"城市名称: {city_name}")
        print(f"国家名称: {country_name}")
        assert city_name == "Beijing"
        assert country_name == "China"
        
        # 测试命名空间注册和获取
        print("\n4. 测试命名空间处理:")
        namespaces = xml_obj.get_namespaces()
        print(f"已注册命名空间: {namespaces}")
        assert "soap" in namespaces
        assert "web" in namespaces
        assert namespaces["soap"] == "http://schemas.xmlsoap.org/soap/envelope/"
        assert namespaces["web"] == "http://www.webserviceX.NET"
        
        # 测试批量注册命名空间
        xml_obj.register_namespaces({
            "temp": "http://tempuri.org/",
            "xsd": "http://www.w3.org/2001/XMLSchema"
        })
        
        namespaces_after = xml_obj.get_namespaces()
        print(f"注册后命名空间: {namespaces_after}")
        assert "temp" in namespaces_after
        assert "xsd" in namespaces_after
        
        # 测试保存和加载
        print("\n5. 测试保存和加载:")
        soap_file = os.path.join(temp_dir, "enhanced_soap_test.xml")
        xml_obj.save_to_file(soap_file)
        print(f"SOAP XML已保存到: {soap_file}")
        
        # 从文件加载
        xml_obj2 = XmlUtils(xml_path=soap_file)
        loaded_city = xml_obj2.get_element_text(".//{http://www.webserviceX.NET}CityName")
        loaded_auth = xml_obj2.get_element_text(".//{http://www.webserviceX.NET}Authentication")
        print(f"加载的城市名称: {loaded_city}")
        print(f"加载的认证信息: {loaded_auth}")
        assert loaded_city == "Beijing"
        assert loaded_auth == "ABC123XYZ"
        
        print("\n所有增强SOAP功能测试通过!")


def test_complex_soap_message():
    """
    测试复杂的SOAP消息处理
    """
    print("\n\n测试复杂SOAP消息处理:")
    
    # 复杂的SOAP响应消息
    complex_soap_response = """<?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <soap:Body>
            <GetUserResponse xmlns="http://example.com/usermanagement">
                <GetUserResult>
                    <User>
                        <Id>12345</Id>
                        <Name>张三</Name>
                        <Email>zhangsan@example.com</Email>
                        <Roles>
                            <Role>
                                <Name>Admin</Name>
                                <Permissions>
                                    <Permission>Read</Permission>
                                    <Permission>Write</Permission>
                                    <Permission>Delete</Permission>
                                </Permissions>
                            </Role>
                            <Role>
                                <Name>User</Name>
                                <Permissions>
                                    <Permission>Read</Permission>
                                </Permissions>
                            </Role>
                        </Roles>
                        <Active>true</Active>
                        <LastLogin>2023-01-01T10:00:00Z</LastLogin>
                    </User>
                </GetUserResult>
            </GetUserResponse>
        </soap:Body>
    </soap:Envelope>"""
    
    xml_obj = XmlUtils(xml_string=complex_soap_response)
    
    # 注册命名空间
    xml_obj.register_namespaces({
        'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
        'usr': 'http://example.com/usermanagement'
    })
    
    # 测试复杂查询
    print("1. 测试复杂查询:")
    
    # 获取用户ID
    user_id = xml_obj.get_element_text(".//{http://example.com/usermanagement}Id")
    print(f"用户ID: {user_id}")
    assert user_id == "12345"
    
    # 获取用户名
    user_name = xml_obj.get_element_text(".//{http://example.com/usermanagement}Name")
    print(f"用户名: {user_name}")
    assert user_name == "张三"
    
    # 获取用户邮箱
    user_email = xml_obj.get_element_text(".//{http://example.com/usermanagement}Email")
    print(f"用户邮箱: {user_email}")
    assert user_email == "zhangsan@example.com"
    
    # 获取角色数量
    roles_count = xml_obj.get_element_count(".//{http://example.com/usermanagement}Role")
    print(f"角色数量: {roles_count}")
    assert roles_count == 2
    
    # 获取权限列表
    permissions = xml_obj.find_elements(".//{http://example.com/usermanagement}Permission")
    permission_texts = [p.text for p in permissions]
    print(f"权限列表: {permission_texts}")
    assert "Read" in permission_texts
    assert "Write" in permission_texts
    assert "Delete" in permission_texts
    
    # 获取特定角色的权限
    admin_permissions = xml_obj.find_elements(".//{http://example.com/usermanagement}Role[1]/{http://example.com/usermanagement}Permissions/{http://example.com/usermanagement}Permission")
    admin_permission_texts = [p.text for p in admin_permissions]
    print(f"管理员权限: {admin_permission_texts}")
    assert len(admin_permission_texts) == 3
    
    user_permissions = xml_obj.find_elements(".//{http://example.com/usermanagement}Role[2]/{http://example.com/usermanagement}Permissions/{http://example.com/usermanagement}Permission")
    user_permission_texts = [p.text for p in user_permissions]
    print(f"用户权限: {user_permission_texts}")
    assert len(user_permission_texts) == 1
    assert user_permission_texts[0] == "Read"
    
    # 测试修改操作
    print("\n2. 测试修改操作:")
    
    # 修改用户名
    xml_obj.set_element_text(".//{http://example.com/usermanagement}Name", "李四")
    
    # 添加新角色
    roles_element = xml_obj.find_element(".//{http://example.com/usermanagement}Roles")
    new_role = ET.SubElement(roles_element, "{http://example.com/usermanagement}Role")
    role_name = ET.SubElement(new_role, "{http://example.com/usermanagement}Name")
    role_name.text = "Auditor"
    
    permissions_element = ET.SubElement(new_role, "{http://example.com/usermanagement}Permissions")
    perm = ET.SubElement(permissions_element, "{http://example.com/usermanagement}Permission")
    perm.text = "Audit"
    
    # 验证修改
    updated_name = xml_obj.get_element_text(".//{http://example.com/usermanagement}Name")
    print(f"更新后的用户名: {updated_name}")
    assert updated_name == "李四"
    
    updated_roles_count = xml_obj.get_element_count(".//{http://example.com/usermanagement}Role")
    print(f"更新后的角色数量: {updated_roles_count}")
    assert updated_roles_count == 3
    
    # 测试转换为字符串
    print("\n3. 测试转换为字符串:")
    xml_string = xml_obj.to_string()
    print("XML字符串长度:", len(xml_string))
    assert "李四" in xml_string
    assert "Auditor" in xml_string
    assert "Audit" in xml_string
    
    print("复杂SOAP消息处理测试通过!")


# 由于我们在方法内部使用了ET，需要导入
import xml.etree.ElementTree as ET


if __name__ == "__main__":
    test_enhanced_soap_features()
    test_complex_soap_message()